import axios from 'axios';
import router from '@/router/index.js';
import userInfoStore from '@/store/userInfoStore.js';

const userInfo = userInfoStore();
// 刷新状态
let isRefreshing = false;
// 重新请求队列
let requestsQueue = [];

function userRefreshTokenApi() {
    return axios({
        url: '/api/user/refreshToken',
        method: 'GET',
        headers: {
            'l-token': userInfo.lToken,
        },
    });
}
// 创建axios
const request = axios.create({
    baseURL: '/api',
    timeout: 5000, // 超时时间
});

// 请求拦截器
request.interceptors.request.use(
    (config) => {
        if (userInfo.token) {
            config.headers.authorization = `Bearer ${userInfo.token}`;
        }
        return config;
    },
    (error) => {
        return Promise.reject(error);
    }
);

// 响应拦截器
request.interceptors.response.use(
    async (response) => {
        if (response.status === 200) {
            userInfo.token = response.headers.newtoken;
            if (response.data.code === 401) {
                userInfo.clearUserInfo();
                ElMessage.error('请重新登录');
                await  router.push('/login');
                return
            }
            if (response.data.code === 4100) {
                const originalRequest = response.config;
                if (!isRefreshing) {
                    isRefreshing = true;
                    try {
                        const res = await userRefreshTokenApi();
                        if (res.data.code === 200) {
                            userInfo.token = res.headers.newtoken;
                            requestsQueue.forEach(cb => cb(userInfo.token));
                            requestsQueue = [];
                        } else {
                            userInfo.clearUserInfo();
                            ElMessage.error('请重新登录');
                            requestsQueue = [];
                            await router.push('/login');
                            return ;
                        }
                    }
                    catch (err) {
                        requestsQueue = [];
                        return Promise.reject(err);
                    } finally {
                        isRefreshing = false;
                    }
                }
                return new Promise(resolve => {
                    requestsQueue.push((token) => {
                        originalRequest.headers.authorization = `Bearer ${token}`;
                        resolve(axios(originalRequest));
                    });
                });
            }
            return response.data;
        }
    },
    (error) => {
        return Promise.reject(error);
    }
);

export default request;
